<template>
  <div class="app-container">
    <div class="head-container">
      <!-- 搜索 -->
      <el-input v-model="listQuery.Filter" clearable size="small" placeholder="搜索..." style="width: 200px;"
        class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.OddNumber" clearable size="small" style="width: 100px;" class="filter-item"
        placeholder="请选择订单号类型">
        <el-option v-for="(item, index) in OddNumberList" :key="index" :label="item.label" :value="item.value"
          :disabled="item.disabled"></el-option>
      </el-select>
      <el-input v-model="listQuery.OrderNumber" clearable size="small" style="width: 150px;" class="filter-item"
        @keyup.enter.native="handleFilter" placeholder="请输入订单号" />
      买家:
      <el-input v-model="listQuery.Buyer" clearable size="small" placeholder="请输入买家姓名" style="width: 150px;"
        class="filter-item" @keyup.enter.native="handleFilter" />
      运单号:
      <el-select v-model="listQuery.IsOrderNumber" clearable size="small" placeholder="请选择是否有单号" style="width: 150px;"
        class="filter-item">
        <el-option label="有单号" value="true" />
        <el-option label="无单号" value="false" />
      </el-select>
      平台店铺:
      <el-select v-model="listQuery.selectedValues" multiple collapse-tags size="small" style="width: 150px;"
        placeholder="请选择平台店铺" filterable>

        <el-option-group label="平台">
          <el-option v-for="item in platformOptions" :key="item.value" :label="item.label" :value="item.value">
            <el-checkbox :label="item.value" v-model="listQuery.selectedValues">{{ item.label }}</el-checkbox>
          </el-option>
        </el-option-group>

        <el-option-group label="店铺">
          <el-option v-for="item in storeOptions" :key="item.value" :label="item.label" :value="item.value">
            <el-checkbox :label="item.value" v-model="listQuery.selectedValues">{{ item.label }}</el-checkbox>
          </el-option>
        </el-option-group>

      </el-select>

      <el-select v-model="listQuery.selectedTime" clearable size="small" style="width: 150px;" class="filter-item">
        <el-option label="最晚发货时间" value="latestShipmentTime"></el-option>
        <el-option label="下单时间" value="orderTime"></el-option>
        <el-option label="仓库接单时间" value="warehouseOrderTime"></el-option>
        <el-option label="付款时间" value="paymentTime"></el-option>
      </el-select>
      &nbsp;
      <el-radio-group v-model="listQuery.selectedRange">
        <el-radio label="today">今天</el-radio>
        <el-radio label="7days">近7天</el-radio>
        <el-radio label="30days">近30天</el-radio>
      </el-radio-group>

      承运商:
      <el-select v-model="listQuery.Carrier" multiple collapse-tags clearable size="small" placeholder="请选择承运商"
        style="width: 150px;" class="filter-item">

        <el-option v-for="item in CarrierList" :key="item.value" :label="item.label" :value="item.value">
          <el-checkbox :label="item.value" v-model="listQuery.Carrier">{{ item.label }}</el-checkbox>
        </el-option>

      </el-select>

      手机:
      <el-input v-model="listQuery.Phone" clearable size="small" placeholder="请输入手机号" style="width: 150px;"
        class="filter-item" @keyup.enter.native="handleFilter" />

      出库类型:
      <el-select v-model="listQuery.OutboundType" clearable size="small" placeholder="请选择出库类型" style="width: 150px;"
        class="filter-item">
        <el-option v-for="(item, index) in OutboundTypeList" :key="index" :label="item.label" :value="item.value" />
      </el-select>

      地区:
      <el-button type="primary" @click="openDialog">地区设置</el-button>

      <el-dialog :visible.sync="dialogVisible" title="地区设置" width="800px">
      <div class="region-settings">
        <div class="header">
          <el-button @click="selectAll">全选</el-button>
          <el-button @click="deselectAll">全不选</el-button>
          <el-button @click="inverseSelection">反选</el-button>
        </div>
        
        <div class="content">
          <div class="left-panel">
            <el-checkbox-group v-model="selectedAreas">
              <div v-for="(region, index) in regions" :key="index" class="region-item">
                <el-checkbox :label="region.name" @change="handleRegionChange(region)">
                  {{ region.name }}
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
          
          <div class="right-panel">
            <el-checkbox-group v-model="selectedCities">
              <div v-for="(city, cityIndex) in currentCities" :key="cityIndex" class="city-item">
                <el-checkbox :label="city">{{ city }}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelection">确定</el-button>
      </span>
    </el-dialog>




      <el-button class="filter-item" type="success" icon="el-icon-search" @click="handleFilter">搜索</el-button>

      <el-button class="filter-item" type="success" icon="el-icon-edit" @click="handleUpdate()">修改</el-button>
      <el-button slot="reference" class="filter-item" type="danger" icon="el-icon-delete"
        @click="handleDelete()">删除</el-button>
    </div>
    <el-table ref="multipleTable" v-loading="listLoading" :data="list" size="small" style="width: 90%;"
      @sort-change="sortChange" @selection-change="handleSelectionChange" @row-click="handleRowClick">
      <el-table-column type="selection" width="44px"></el-table-column>
      <el-table-column label="提醒" prop="reminder" align="center" />
      <el-table-column label="外部状态" prop="externalStatus" align="center" />
      <el-table-column label="买家留言" prop="buyerMessage" align="center" />
      <el-table-column label="订单备注" prop="orderNote" align="center" />
      <el-table-column label="库位库存" prop="locationStock" align="center" />
      <el-table-column label="承运商" prop="carrier" align="center" />
      <el-table-column label="运单号" prop="trackingNumber" align="center" />
      <el-table-column label="配送方式" prop="deliveryMethod" align="center" />
      <el-table-column label="买家" prop="buyer" align="center" />
      <el-table-column label="收货人" prop="consignee" align="center" />
      <el-table-column label="详细地址" prop="detailedAddress" align="center" />
      <el-table-column label="手机" prop="phone" align="center" />
      <el-table-column label="实付" prop="pay" align="center" />
      <el-table-column label="优惠" prop="discount" align="center" />
      <el-table-column label="运费" prop="freight" align="center" />
      <el-table-column label="重量" prop="weight" align="center" />
      <el-table-column label="估重" prop="weightEstimation" align="center" />
      <el-table-column label="商品总数" prop="totalGoods" align="center" />
      <el-table-column label="下单时间" prop="orderTime" align="center" />
      <el-table-column label="订单号" prop="orderNumber" align="center" />
      <el-table-column label="外部订单号" prop="externalOrderNumber" align="center" />
      <el-table-column label="线上订单号" prop="onlineOrderNumber" align="center" />
      <el-table-column label="平台店铺" prop="platformStore" align="center" />
      <el-table-column label="付款时间" prop="paymentTime" align="center" />
      <el-table-column label="仓库接单时间" prop="warehouseOrderTime" align="center" />
      <el-table-column label="炼选区域" prop="pickingArea" align="center" />
      <el-table-column label="出库类型" prop="outboundType" align="center" />
      <el-table-column label="品牌" prop="brand" align="center" />
      <el-table-column label="归属波次" prop="attributionWave" align="center" />
      <el-table-column label="等待超时时间" prop="waitingTimeoutTime" align="center" />
      <el-table-column label="到货时间" prop="arrivalTime" align="center" />
      <el-table-column label="体积" prop="volume" align="center" />
      <el-table-column label="标记" prop="mark" align="center" />
      <el-table-column label="最晚发货时间" prop="latestShipmentTime" align="center" />
      <el-table-column label="剩余发货时间" prop="remainingShipmentTime" align="center" />
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)" icon="el-icon-edit" />
          <el-button type="danger" size="mini" @click="handleDelete(row)" icon="el-icon-delete" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="totalCount > 0" :total="totalCount" :page.sync="page" :limit.sync="listQuery.MaxResultCount"
      @pagination="getList" />
  </div>
</template>
<script>
import Pagination from "@/components/Pagination";
import permission from "@/directive/permission/index.js";
const defaultForm = {
  id: null,
  Reminder: null,
  ExternalStatus: null,
  BuyerMessage: null,
  OrderNote: null,
  LocationStock: null,
  Carrier: null,
  TrackingNumber: null,
  DeliveryMethod: null,
  Buyer: null,
  Consignee: null,
  DetailedAddress: null,
  Phone: null,
  Pay: null,
  Discount: null,
  freight: null,
  weight: null,
  WeightEstimation: null,
  TotalGoods: null,
  OrderTime: null,
  OrderNumber: null,
  ExternalOrderNumber: null,
  OnlineOrderNumber: null,
  PlatformStore: null,
  PaymentTime: null,
  WarehouseOrderTime: null,
  PickingArea: null,
  OutboundType: null,
  Brand: null,
  AttributionWave: null,
  WaitingTimeoutTime: null,
  ArrivalTime: null,
  Volume: null,
  Mark: null,
  LatestShipmentTime: null,
  RemainingShipmentTime: null,
}
export default {
  name: 'WaitingOutbound',
  components: {
    Pagination
  },
  directives: {
    permission
  },
  props: [],
  data() {
    return {
      form: Object.assign({}, defaultForm),
      list: null,
      totalCount: 0,
      listLoading: true,
      formLoading: false,
      listQuery: {
        Filter: '',
        Sorting: '',
        SkipCount: 0,
        MaxResultCount: 10,
        OddNumber: "1",
        OrderNumber: '',
        Buyer: '',
        IsOrderNumber: '',
        selectedValues: [],
        selectedTime: 'warehouseOrderTime',
        selectedRange: '7days', // 默认选中"近7天"
        Carrier: [],

      },
      page: 1,
      dialogFormVisible: false,
      multipleSelection: [],
      formTitle: '',
      isEdit: false,
      OddNumberList: [],
      OutboundTypeList: [],
      platformOptions: [
        { label: '淘宝', value: 'taobao' },
        { label: '拍拍', value: 'paipai' },
        { label: '京东', value: 'jingdong' },
        { label: '天猫', value: 'tmall' },
        { label: '唯品会', value: 'vipshop' },
        { label: '苏宁', value: 'suning' },
        { label: '拼多多', value: 'pinduoduo' },
        { label: '1688', value: '1688' }
      ],
      storeOptions: [
        { label: '', value: '' },
      ],
      CarrierList: [],
      dialogVisible: false,
      selectedAreas: [],
      selectedCities: {},
      regions: [
        { name: '北京', cities: ['北京市'], expanded: false },
        { name: '天津', cities: ['天津市'], expanded: false },
        { name: '河北省', cities: ['石家庄市', '唐山市', '保定市'], expanded: false },
        { name: '山西省', cities: ['太原市', '大同市'], expanded: false },
        { name: '内蒙古自治区', cities: ['呼和浩特市', '包头市'], expanded: false },
        { name: '辽宁省', cities: ['沈阳市', '大连市'], expanded: false },
        { name: '吉林省', cities: ['长春市'], expanded: false },
        { name: '黑龙江省', cities: ['哈尔滨市'], expanded: false }
        // 可以继续添加其他省和城市
      ]
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getList()
    this.getOddNumberList()
    this.getCarrierList()
    this.getOutboundType()
  },
  mounted() { },
  methods: {
    openDialog() {
      this.dialogVisible = true;
      this.resetSelections();
    },
    resetSelections() {
      this.selectedAreas = [];
      this.selectedCities = {};
      this.regions.forEach(region => {
        this.selectedCities[region.name] = [];
      });
    },
    selectAll() {
      this.selectedAreas = this.regions.map(region => region.name);
      this.regions.forEach(region => {
        this.selectedCities[region.name] = region.cities;
      });
    },
    deselectAll() {
      this.selectedAreas = [];
      this.regions.forEach(region => {
        this.selectedCities[region.name] = [];
      });
    },
    inverseSelection() {
      this.regions.forEach(region => {
        if (this.selectedAreas.includes(region.name)) {
          this.selectedAreas.splice(this.selectedAreas.indexOf(region.name), 1);
          this.selectedCities[region.name] = [];
        } else {
          this.selectedAreas.push(region.name);
          this.selectedCities[region.name] = region.cities;
        }
      });
    },
    handleRegionChange(region) {
      region.expanded = !region.expanded;
    },
    confirmSelection() {
      console.log('选择的区域:', this.selectedAreas);
      console.log('选择的城市:', this.selectedCities);
      this.dialogVisible = false;
    },
    getList() {
      this.listLoading = true;
      this.listQuery.SkipCount = (this.page - 1) * this.listQuery.MaxResultCount;
      this.$axios.gets('/api/business/WaitingOutbound', this.listQuery).then(response => {
        this.list = response.items;
        this.totalCount = response.totalCount;
        this.listLoading = false;
      });
    },
    getOddNumberList() {
      this.$axios.gets('/api/base/dictDetails/list?name=' + "OddNumber").then(response => {
        this.OddNumberList = response.items;
      });
    },
    getCarrierList() {
      this.$axios.gets('/api/base/dictDetails/list?name=' + "Carrier").then(response => {
        this.CarrierList = response.items;
      });
    },
    getOutboundType() {
      this.$axios.gets('/api/base/dictDetails/list?name=' + "OutboundType").then(response => {
        this.OutboundTypeList = response.items;
      });
    },
    fetchData(id) {
      this.$axios.gets('/api/business/WaitingOutbound/' + id).then(response => {
        this.form = response;
      });
    },
    handleFilter() {
      this.page = 1;
      this.getList();
    },
    handleCreate() {
      this.formTitle = '新增待出库';
      this.isEdit = false;
      this.dialogFormVisible = true;
    },
    handleDelete(row) {
      var params = [];
      let alert = '';
      if (row) {
        params.push(row.id);
        alert = row.name;
      }
      else {
        if (this.multipleSelection.length === 0) {
          this.$message({
            message: '未选择',
            type: 'warning'
          });
          return;
        }
        this.multipleSelection.forEach(element => {
          let id = element.id;
          params.push(id);
        });
        alert = '选中项';
      }
      this.$confirm('是否删除' + alert + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.posts('/api/business/WaitingOutbound/delete', params).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          });
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleUpdate(row) {
      this.formTitle = '修改待出库';
      this.isEdit = true;
      if (row) {
        this.fetchData(row.id);
        this.dialogFormVisible = true;
      }
      else {
        if (this.multipleSelection.length != 1) {
          this.$message({
            message: '编辑必须选择单行',
            type: 'warning'
          });
          return;
        }
        else {
          this.fetchData(this.multipleSelection[0].id);
          this.dialogFormVisible = true;
        }
      }
    },
    save() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.formLoading = true;
          this.form.roleNames = this.checkedRole;
          if (this.isEdit) {
            this.$axios.posts('/api/business/WaitingOutbound/data-post', this.form).then(response => {
              this.formLoading = false;
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              });
              this.dialogFormVisible = false;
              this.getList();
            }).catch(() => {
              this.formLoading = false;
            });
          }
          else {
            this.$axios.posts('/api/business/WaitingOutbound/data-post', this.form).then(response => {
              this.formLoading = false;
              this.$notify({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              });
              this.dialogFormVisible = false;
              this.getList();
            }).catch(() => {
              this.formLoading = false;
            });
          }
        }
      });
    },
    sortChange(data) {
      const {
        prop,
        order
      } = data;
      if (!prop || !order) {
        this.handleFilter();
        return;
      }
      this.listQuery.Sorting = prop + ' ' + order;
      this.handleFilter();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleRowClick(row, column, event) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    cancel() {
      this.form = Object.assign({}, defaultForm);
      this.dialogFormVisible = false;
      this.$refs.form.clearValidate();
    },
  }
}

</script>
<style scoped>
.region-settings {
  max-height: 400px;
  overflow-y: auto;
}
.header {
  margin-bottom: 10px;
}
.region-item {
  margin-bottom: 10px;
}
.city-group {
  padding-left: 20px;
  padding-top: 5px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
